from django.shortcuts import render
from django.views.generic.base import View
# Create your views here.
from mgproject.apps.newsapp.models import NewsChannel, Article
from django.http import HttpResponseNotFound
from django.core.paginator import Paginator, EmptyPage


class IndexView(View):
    def get(self,request,channel_id=1,page_num=1):
        """"
        新闻列表展示功能
        """
        #huoqudangqianpindaoxiade leibieid
        try:
            newschannel=NewsChannel.objects.get(id=channel_id)
        except NewsChannel.DoesNotExist:
            return HttpResponseNotFound('donot found channel_id')
        else:
            category_id_list=[category.id for category in newschannel.newscategory_set.all() if category]
        # chakan dangqianpindaoxia desuoyouwenzhang
        article = Article.objects.filter(category_id__in=category_id_list).order_by('id')
        # chuangjianfenyeduixiang
        page_obj=Paginator(article,3)
        #huoqu dangqian ye shuju
        try:
            page_articles=page_obj.page(page_num)
        except EmptyPage:
            return HttpResponseNotFound('NOT FOUND PAGE NUMBER')

        return render(request,'newsapp/index.html',{'articles':article,'channel_id':channel_id})
